package com.gzu.finalwork.user.service;

import com.gzu.finalwork.entity.user.*;
import com.gzu.finalwork.user.config.AjaxResult;
import com.gzu.finalwork.user.mapper.AddressesMapper;
import com.gzu.finalwork.user.mapper.DeliveryOrdersMapper;
import com.gzu.finalwork.user.mapper.UserMapper;
import com.gzu.finalwork.user.repository.DeliveryTrackRepository;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class DeliveryTrackService {
    @Autowired
    private  DeliveryTrackRepository trackRepository;
    @Autowired
    private  DeliveryOrdersMapper deliveryOrdersMapper;
    @Autowired
    private AddressesMapper addressesMapper;
    @Autowired
    private  AmapService amapService;
    @Autowired
    private EmailService emailService;
    @Autowired
    private UserMapper userMapper;

    // 创建物流轨迹
    public DeliveryTrack createTrack(Long deliveryOrderId, String orderNumber) {
        DeliveryTrack track = new DeliveryTrack();
        track.setDeliveryOrderId(deliveryOrderId);
        track.setOrderNumber(orderNumber);
        track.setCreatedAt(LocalDateTime.now());
        track.setUpdatedAt(LocalDateTime.now());

        // 获取订单信息，设置初始位置为寄件人地址
        DeliveryOrders order = deliveryOrdersMapper.selectByDeliveryOrderId(deliveryOrderId);
        if (order != null && order.getSenderAddress() != null) {
            // 尝试通过地址获取坐标
            Addresses senderAddr = addressesMapper.selectByFullAddress(order.getSenderAddress());
            if (senderAddr != null && senderAddr.hasCoordinates()) {
                List<DeliveryTrack.TrackRecord> record = new ArrayList<>();
                // 创建一个新的TrackRecord对象并添加到列表中
                DeliveryTrack.TrackRecord trackRecord = new DeliveryTrack.TrackRecord();
                trackRecord.setTimestamp(LocalDateTime.now());
                trackRecord.setStatus(1); // 已下单
                trackRecord.setDescription("已下单");
                trackRecord.setLocation(new DeliveryTrack.Location());
                trackRecord.getLocation().setLongitude(senderAddr.getLongitude());
                trackRecord.getLocation().setLatitude(senderAddr.getLatitude());
                trackRecord.getLocation().setAddress(order.getSenderAddress());
                trackRecord.setOperator("系统");
                record.add(trackRecord); // 将TrackRecord对象添加到列表中

                track.setTrackRecords(record);
            }
        }
        return trackRepository.save(track);
    }

    // 添加轨迹记录
    public Object addTrackRecord(Long deliveryOrderId, DeliveryTrack.TrackRecord record) {
        DeliveryTrack tracks = trackRepository.findByDeliveryOrderId(deliveryOrderId);
        if (tracks != null) {
            if (record.getTimestamp() == null) {
                record.setTimestamp(LocalDateTime.now());
            }
            DeliveryTrack.TrackRecord record1 = new DeliveryTrack.TrackRecord();
            if(record.getTimestamp() == null){
                record1.setTimestamp(LocalDateTime.now());
            }else{
                record1.setTimestamp(record.getTimestamp());
            }
            record1.setStatus(record.getStatus());
            record1.setDescription(record.getDescription());
            if (record.getOperator() == null) {
                record1.setOperator("系统");
            }else {
                record1.setOperator(record.getOperator());
            }
            if (record.getLocation() == null || record.getLocation().getAddress() == null) {
                return AjaxResult.error(-1, "地址不能为空");
            } else {
                record1.setLocation(new DeliveryTrack.Location());
                DeliveryTrack.Location addr = convertAddressToLocation(record.getLocation().getAddress());
                if (addr == null) {
                    return AjaxResult.error(-2, "地址不存在");
                }
                record1.getLocation().setLatitude(addr.getLatitude());
                record1.getLocation().setLongitude(addr.getLongitude());
                record1.getLocation().setAddress(addr.getAddress());
            }
            tracks.getTrackRecords().add(record1);
            trackRepository.save(tracks);
            //同步更新订单状态
            updateOrderStatus(deliveryOrderId, record.getStatus());
            // 异步发送邮件通知到RabbitMQ队列
            sendEmailNotificationAsync(deliveryOrderId, record);
            return AjaxResult.success("记录添加成功");
        } else {
            return AjaxResult.error(-3, "未找到对应的配送单");
        }
    }

    //删除订单轨迹
    public void deleteTrackByOrderId(Long deliveryOrderId){
         trackRepository.deleteByDeliveryOrderId(deliveryOrderId);
    }

    // 根据订单ID查询轨迹
    public DeliveryTrack getTrackByOrderId(Long deliveryOrderId) {
        return trackRepository.findByDeliveryOrderId(deliveryOrderId);
    }

    // 根据订单编号查询轨迹
    public DeliveryTrack getTrackByOrderNumber(String orderNumber) {
        return trackRepository.findByOrderNumber(orderNumber);
    }

    //将地址转换为坐标
    public DeliveryTrack.Location convertAddressToLocation(String  fullAddress) {
        List<String> geocodeResult = amapService.geocode(fullAddress);
        if (geocodeResult != null && geocodeResult.size() >= 2) {
            // 直接从List中获取经度和纬度
            String longitudeStr = geocodeResult.get(0);
            String latitudeStr = geocodeResult.get(1);
            Double longitude = Double.parseDouble(longitudeStr.trim());
            Double latitude = Double.parseDouble(latitudeStr.trim());
            DeliveryTrack.Location location = new DeliveryTrack.Location();
            location.setLongitude(longitude);
            location.setLatitude(latitude);
            location.setAddress(fullAddress);
            return location;
        }else {
            return null;
        }

    }


    // 获取订单完整跟踪信息（包含订单详情）
    public Object getCompleteTrackInfo(String orderNumber) {
        DeliveryOrders orders = deliveryOrdersMapper.selectByDeliveryOrderNo(orderNumber);
        if (orders != null) {
            DeliveryTrack track = getTrackByOrderId(orders.getDeliveryOrderId());
            if (track != null) {
                // 获取订单详情
                DeliveryOrders order = deliveryOrdersMapper.selectByDeliveryOrderId(orders.getDeliveryOrderId());
                // 为每轨迹创建OrderTrackInfo对象
                OrderTrackInfo info = new OrderTrackInfo();
                info.setOrder(order);
                info.setTrack(track);
                return AjaxResult.success(info);
            }else {
                return AjaxResult.error(-1,"该订单无完整的物流信息");
            }
        }else {
            return AjaxResult.error(-2,"未找到该订单");
        }
    }

    // 同步更新订单状态
    public void updateOrderStatus(Long deliveryOrderId, Integer trackStatus) {
        DeliveryOrders order = deliveryOrdersMapper.selectByDeliveryOrderId(deliveryOrderId);
        if (order != null) {
            Integer newOrderStatus = null;
            switch (trackStatus){
                case 1: // 已下单
                case 2: // 待揽件
                    newOrderStatus = 0; // 待揽收
                    break;
                case 3: // 已揽件
                    newOrderStatus = 1; // 待发货
                    break;
                case 4: // 运输中
                    newOrderStatus = 2; // 运输中
                    break;
                case 5: // 已到达
                    newOrderStatus = 3; // 待签收
                    break;
                case 6: // 已签收
                    newOrderStatus = 4; // 已完成
                    break;
                default:
                    // 未知状态，不更新
                    return;
            }
            
            // 只有当新状态不同时才更新，避免重复更新
            if (!newOrderStatus.equals(order.getOrderStatus())) {
                order.setOrderStatus(newOrderStatus);
                order.setUpdatedAt(LocalDateTime.now());
                deliveryOrdersMapper.updateStatusByDeliveryOrderId(order);
                log.info("订单状态已更新: 订单ID={}, 轨迹状态={}, 新订单状态={}", 
                        deliveryOrderId, trackStatus, newOrderStatus);
            }
        }
    }

    // 异步发送邮件通知
    private void sendEmailNotificationAsync(Long deliveryOrderId, DeliveryTrack.TrackRecord record) {
        try {
            DeliveryOrders order = deliveryOrdersMapper.selectByDeliveryOrderId(deliveryOrderId);
            Users users = userMapper.selectByUserId(order.getUserId());
            if (order != null && users.getEmail() != null) {
                String subject = buildEmailSubject(order, record);
                String content = buildEmailContent(order, record);

                EmailMessage emailMessage = new EmailMessage(
                        users.getEmail(),
                        subject,
                        content,
                        order.getOrderNumber(),
                        record.getStatus(),
                        record.getOperator()
                );
                emailService.sendEmailMessage(emailMessage);
            }
        } catch (Exception e) {
            log.error("发送轨迹更新邮件通知失败: {}", e.getMessage(), e);
        }
    }

    // 构建邮件主题
    private String buildEmailSubject(DeliveryOrders order, DeliveryTrack.TrackRecord record) {
        String statusText = getStatusText(record.getStatus());
        return String.format("【配送通知】订单%s - %s", order.getOrderNumber(), statusText);
    }

    // 构建邮件内容
    private String buildEmailContent(DeliveryOrders order, DeliveryTrack.TrackRecord record) {
        String statusText = getStatusText(record.getStatus());
        return String.format(
                "尊敬的客户，\n\n" +
                        "您的订单 %s 状态已更新：\n\n" +
                        "当前状态：%s\n" +
                        "当前位置：%s\n" +
                        "操作员：%s\n" +
                        "更新时间：%s\n\n" +
                        "如有疑问，请联系客服。\n\n" +
                        "感谢您的使用！",
                order.getOrderNumber(),
                statusText,
                record.getLocation().getAddress(),
                record.getOperator(),
                record.getTimestamp().format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
        );
    }

    // 获取状态文本
    private String getStatusText(Integer status) {
        switch (status) {
            case 1: return "已下单";
            case 2: return "待揽件";
            case 3: return "已揽件";
            case 4: return "配送中";
            case 5: return "已到达";
            case 6: return "已签收";
            default: return "状态未知";
        }
    }


    @Data
    //订单跟踪信息封装类
    public static class OrderTrackInfo {
        private DeliveryOrders order;
        private DeliveryTrack track;

    }
}